import os
from datetime import datetime
from os.path import join

import torch
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

from ALE.data.dataset_gzsl import Dataset
from ALE.flags import parser
from ALE.models.confg_model import config_model
from common_utils.Evaluator import zsl_acc_gzsl2, zsl_acc_gzsl, zsl_acc2, Evaluator
from common_utils.utils import load_args

device = 'cuda' if torch.cuda.is_available() else 'cpu'

parser.add_argument('--phase', default='gzsql_test', help='训练阶段')
def main():
    print(os.getcwd())
    args = parser.parse_args()
    load_args(args.config, args)
    TIMESTAMP = "{0:%Y-%m-%dT%H-%M-%S/}".format(datetime.now())
    logpath = os.path.join(args.cv_dir, args.name, 'tensorboard/'+args.phase+"/"+TIMESTAMP)
    os.makedirs(logpath, exist_ok=True)
    testSet = Dataset(data_dir=join(args.data_root,args.data_dir),
                      dataset=args.dataset, phase=args.phase)
    writer = SummaryWriter(log_dir= logpath, flush_secs=30)
    model, optimizer = config_model(args = args,feat_dim=testSet.feat_dim,attr_dim=testSet.attr_dim)
    model.eval()
    modelPath = os.path.join(args.cv_dir, args.name)
    checkpoint = torch.load(join(modelPath, "checkpoint"),map_location= device)
    model.load_state_dict(checkpoint['model_state_dict'])
    attrs = torch.index_select(testSet.sig, dim=0,
                              index=testSet.labels_test)
    _, test_preds = model(imgs=testSet.data.to(device), attrs=attrs.to(device),labels = testSet.labels_test.to(device),sig = testSet.sig.to(device))
    # HM = 2 * acc_seen_classes * acc_unseen_classes / (acc_seen_classes + acc_unseen_classes)
    train_evaluator = Evaluator(50)
    acc_classes = train_evaluator.evaluate_label_predictions(predictions=test_preds.data.cpu(), truth=testSet.labels_test.data.cpu())
    print(f'all:{acc_classes};')
if __name__ == '__main__':
    main()
